package com.ftg.learn.code.servcie.impl;

import com.ftg.learn.code.servcie.CodeService;
import com.ftg.learn.code.utils.AliDyUtil;
import com.ftg.learn.common.constant.CodeConstant;
import com.ftg.learn.common.dto.LoginByPhoneDto;
import com.ftg.learn.common.exception.PhoneErrorException;
import com.ftg.learn.common.result.Result;
import com.ftg.learn.common.utils.PhoneValidator;
import com.ftg.learn.common.utils.VerificationCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

import static com.ftg.learn.common.constant.MessageErrorConstant.PHONE_ERROR;
import static com.ftg.learn.common.constant.RedisKeyConstant.USER_CODE;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AliDyUtil aliDyUtil;
    @Override
    public Result<String> getCode(String phone) {
        boolean validChinaMainlandPhone = PhoneValidator.isValidChinaMainlandPhone(phone);
        if(!validChinaMainlandPhone){
            throw new PhoneErrorException(PHONE_ERROR);
        }
        String key = USER_CODE+phone;
        //生成纯数字的验证码
        String code = aliDyUtil.sendSms(phone);
        if(code==null){
            return Result.build(CodeConstant.INTERNAL_SERVER_ERROR, PHONE_ERROR);
        }
        redisTemplate.opsForValue().set(key,code);
        redisTemplate.expire(key,3, TimeUnit.MINUTES);
        return Result.build(CodeConstant.OK, "验证码生成成功");
    }

    @Override
    public boolean validateCode(LoginByPhoneDto loginByPhoneDto) {
        String key = USER_CODE+loginByPhoneDto.getPhone();
        String redisCode = redisTemplate.opsForValue().get(key);
        if(redisCode==null){
            return false;
        }
        if(redisCode.equals(loginByPhoneDto.getCode())){
            return true;
        }
        return false;
    }
}
